using System;
using System.IO;
using System.Text;

namespace StarSkipGame
{
    /// <summary>
    /// 游戏设置类，管理所有用户可配置的游戏选项
    /// </summary>
    public class GameSettings
    {
        private const string SETTINGS_FILE = "settings.txt";
        
        // 音效设置
        public bool SoundEffectsEnabled { get; set; }
        public bool BackgroundMusicEnabled { get; set; }
        public float SoundEffectsVolume { get; set; }
        public float BackgroundMusicVolume { get; set; }
        
        // 游戏设置
        public bool ShowFPS { get; set; }
        public bool ShowParticleEffects { get; set; }
        public bool ShowTrails { get; set; }
        public int DefaultGameMode { get; set; } // 0 = Classic
        
        // 界面设置
        public bool ShowGameStatistics { get; set; }
        public bool ShowAchievementNotifications { get; set; }
        
        // 控制设置
        public bool InvertControls { get; set; }
        public float MouseSensitivity { get; set; }
        
        // 演示模式设置
        public bool AutoDemoMode { get; set; }
        public float DemoModeDuration { get; set; } // 演示模式持续时间（秒）
        
        // 性能设置
        public int TargetFrameRate { get; set; }
        public bool EnableVSync { get; set; }
        
        private static GameSettings instance;
        private static readonly object lockObject = new object();
        
        /// <summary>
        /// 单例模式获取设置实例
        /// </summary>
        public static GameSettings Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockObject)
                    {
                        if (instance == null)
                        {
                            instance = new GameSettings();
                        }
                    }
                }
                return instance;
            }
        }
        
        private GameSettings()
        {
            // 初始化默认值
            SoundEffectsEnabled = true;
            BackgroundMusicEnabled = true;
            SoundEffectsVolume = 1.0f;
            BackgroundMusicVolume = 0.7f;
            ShowFPS = false;
            ShowParticleEffects = true;
            ShowTrails = true;
            DefaultGameMode = 0;
            ShowGameStatistics = true;
            ShowAchievementNotifications = true;
            InvertControls = false;
            MouseSensitivity = 1.0f;
            AutoDemoMode = false;
            DemoModeDuration = 30.0f; // 默认演示30秒
            TargetFrameRate = 60;
            EnableVSync = true;

            LoadSettings();
        }
        
        /// <summary>
        /// 加载游戏设置
        /// </summary>
        public void LoadSettings()
        {
            try
            {
                if (File.Exists(SETTINGS_FILE))
                {
                    string[] lines = File.ReadAllLines(SETTINGS_FILE, Encoding.UTF8);
                    foreach (string line in lines)
                    {
                        if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#"))
                            continue;
                            
                        string[] parts = line.Split('=');
                        if (parts.Length == 2)
                        {
                            string key = parts[0].Trim();
                            string value = parts[1].Trim();
                            
                            switch (key)
                            {
                                case "SoundEffectsEnabled":
                                    bool.TryParse(value, out bool soundEffects);
                                    SoundEffectsEnabled = soundEffects;
                                    break;
                                case "BackgroundMusicEnabled":
                                    bool.TryParse(value, out bool backgroundMusic);
                                    BackgroundMusicEnabled = backgroundMusic;
                                    break;
                                case "SoundEffectsVolume":
                                    float.TryParse(value, out float soundVolume);
                                    SoundEffectsVolume = Math.Max(0.0f, Math.Min(1.0f, soundVolume));
                                    break;
                                case "BackgroundMusicVolume":
                                    float.TryParse(value, out float musicVolume);
                                    BackgroundMusicVolume = Math.Max(0.0f, Math.Min(1.0f, musicVolume));
                                    break;
                                case "ShowFPS":
                                    bool.TryParse(value, out bool showFPS);
                                    ShowFPS = showFPS;
                                    break;
                                case "ShowParticleEffects":
                                    bool.TryParse(value, out bool showParticles);
                                    ShowParticleEffects = showParticles;
                                    break;
                                case "ShowTrails":
                                    bool.TryParse(value, out bool showTrails);
                                    ShowTrails = showTrails;
                                    break;
                                case "DefaultGameMode":
                                    int.TryParse(value, out int gameMode);
                                    DefaultGameMode = Math.Max(0, Math.Min(4, gameMode));
                                    break;
                                case "ShowGameStatistics":
                                    bool.TryParse(value, out bool showStats);
                                    ShowGameStatistics = showStats;
                                    break;
                                case "ShowAchievementNotifications":
                                    bool.TryParse(value, out bool showAchievements);
                                    ShowAchievementNotifications = showAchievements;
                                    break;
                                case "InvertControls":
                                    bool.TryParse(value, out bool invertControls);
                                    InvertControls = invertControls;
                                    break;
                                case "MouseSensitivity":
                                    float.TryParse(value, out float mouseSensitivity);
                                    MouseSensitivity = Math.Max(0.1f, Math.Min(3.0f, mouseSensitivity));
                                    break;
                                case "TargetFrameRate":
                                    int.TryParse(value, out int frameRate);
                                    TargetFrameRate = Math.Max(30, Math.Min(120, frameRate));
                                    break;
                                case "EnableVSync":
                                    bool.TryParse(value, out bool enableVSync);
                                    EnableVSync = enableVSync;
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 如果加载失败，使用默认设置
                Console.WriteLine("加载设置文件失败: " + ex.Message);
            }
        }
        
        /// <summary>
        /// 保存游戏设置
        /// </summary>
        public void SaveSettings()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("# 星际躲避游戏设置文件");
                sb.AppendLine("# 音效设置");
                sb.AppendLine("SoundEffectsEnabled=" + SoundEffectsEnabled);
                sb.AppendLine("BackgroundMusicEnabled=" + BackgroundMusicEnabled);
                sb.AppendLine("SoundEffectsVolume=" + SoundEffectsVolume);
                sb.AppendLine("BackgroundMusicVolume=" + BackgroundMusicVolume);
                sb.AppendLine();
                sb.AppendLine("# 游戏设置");
                sb.AppendLine("ShowFPS=" + ShowFPS);
                sb.AppendLine("ShowParticleEffects=" + ShowParticleEffects);
                sb.AppendLine("ShowTrails=" + ShowTrails);
                sb.AppendLine("DefaultGameMode=" + DefaultGameMode);
                sb.AppendLine();
                sb.AppendLine("# 界面设置");
                sb.AppendLine("ShowGameStatistics=" + ShowGameStatistics);
                sb.AppendLine("ShowAchievementNotifications=" + ShowAchievementNotifications);
                sb.AppendLine();
                sb.AppendLine("# 控制设置");
                sb.AppendLine("InvertControls=" + InvertControls);
                sb.AppendLine("MouseSensitivity=" + MouseSensitivity);
                sb.AppendLine();
                sb.AppendLine("# 性能设置");
                sb.AppendLine("TargetFrameRate=" + TargetFrameRate);
                sb.AppendLine("EnableVSync=" + EnableVSync);
                
                File.WriteAllText(SETTINGS_FILE, sb.ToString(), Encoding.UTF8);
            }
            catch (Exception ex)
            {
                Console.WriteLine("保存设置文件失败: " + ex.Message);
            }
        }
        
        /// <summary>
        /// 重置为默认设置
        /// </summary>
        public void ResetToDefaults()
        {
            SoundEffectsEnabled = true;
            BackgroundMusicEnabled = true;
            SoundEffectsVolume = 1.0f;
            BackgroundMusicVolume = 0.7f;
            ShowFPS = false;
            ShowParticleEffects = true;
            ShowTrails = true;
            DefaultGameMode = 0;
            ShowGameStatistics = true;
            ShowAchievementNotifications = true;
            InvertControls = false;
            MouseSensitivity = 1.0f;
            TargetFrameRate = 60;
            EnableVSync = true;
            
            SaveSettings();
        }
        
        /// <summary>
        /// 应用设置到游戏引擎
        /// </summary>
        public void ApplyToGameEngine(GameEngine gameEngine)
        {
            if (gameEngine.SoundManager != null)
            {
                gameEngine.SoundManager.SetSoundEffectsEnabled(SoundEffectsEnabled);
                gameEngine.SoundManager.SetBackgroundMusicEnabled(BackgroundMusicEnabled);
                gameEngine.SoundManager.SetSoundEffectsVolume(SoundEffectsVolume);
                gameEngine.SoundManager.SetBackgroundMusicVolume(BackgroundMusicVolume);
            }
            
            if (gameEngine.GameModeManager != null)
            {
                gameEngine.GameModeManager.SetGameMode((GameMode)DefaultGameMode);
            }
        }
    }
} 